package com.zmt.content.service.jobHandler;

import com.xuecheng.messagesdk.model.po.MqMessage;
import com.xuecheng.messagesdk.service.MessageProcessAbstract;
import com.xuecheng.messagesdk.service.MqMessageService;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.zmt.content.feignClient.SearchServiceClient;
import com.zmt.content.feignClient.CourseIndex;
import com.zmt.content.mapper.CoursePublishMapper;
import com.zmt.content.po.CoursePublish;
import com.zmt.content.service.CoursePublishService;
import com.zmt.xuechengplusbase.exception.xuechengplusException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.File;


@Slf4j
@Component
public class CoursePublishJob extends MessageProcessAbstract {
    @Autowired
    private CoursePublishService coursePublishService;

    @Autowired
    private SearchServiceClient searchServiceClient;

    @Autowired
    private CoursePublishMapper coursePublishMapper;




    @XxlJob("CoursePublishJobHandler")
    public void coursePublishJobHandler() throws Exception{
        int shardIndex = XxlJobHelper.getShardIndex();
        int shardTotal = XxlJobHelper.getShardTotal();

        process(shardIndex,shardTotal,"course_publish",30,60);

    }

    /**
     * 消息任务处理
     * @param mqMessage 执行任务内容
     * @return
     */
    @Override
    public boolean execute(MqMessage mqMessage) {
        Long courseId = Long.valueOf(mqMessage.getBusinessKey1());
        //向minio中生成静态页面
        generateCourseHtml(mqMessage,courseId);
        //向ES中做索引
        saveCourseIndex(mqMessage,courseId);
        // TODO 向Redis中做缓存（都没有能保存的东西，焯！）
//        saveRedis(mqMessage,courseId);

        /**
         * 思路：首先就是，要存什么东西进入Redis。
         * 首先是搜索页面的分类？在课程多了之后，这些基本就是不变的资源
         * 其次是静态页面中的资源，但是已经在minio存储了欸？再存储Redis合适吗？而且课程多了之后，拿内存干这个？或许可以存储minio的访问地址
         * 保存完存储地址后，直接写入Redis，那么每次访问课程id时，直接去Redis拿数据
         * 首页的话，给的资源是直接写死了，没有可以访问数据库的地方，真没啥可以存储的……
         * 似乎也没有什么可以存储的了
         */
        return true;
    }

    /**
     * 保存课程id以及访问路径到Redis
     * @param mqMessage
     * @param courseId
     */
    private void saveRedis(MqMessage mqMessage, Long courseId) {
        //TODO
        Long taskId = mqMessage.getId();
        MqMessageService mqMessageService = this.getMqMessageService();
        int stageThree = mqMessageService.getStageThree(taskId);
        if (stageThree>0){
            log.debug("保存Redis成功，无需再次处理");
            return;
        }

        coursePublishService.saveRedis(courseId);
    }

    /**
     * 生成静态页面
     * @param mqMessage
     * @param courseId
     */
    private void generateCourseHtml(MqMessage mqMessage, Long courseId) {
        Long taskId = mqMessage.getId();
        MqMessageService mqMessageService = this.getMqMessageService();

        //根据主键id查询到对应状态码，看是否还需要继续执行
        int stageOne = mqMessageService.getStageOne(taskId);
        if (stageOne>0){
            log.debug("静态化完成，无需处理.....");
            return;
        }

        //具体实现操作
        File file = coursePublishService.generateCourseHtml(courseId);
        if (file==null){
            return;
        }
        coursePublishService.uploadCourseHtml(courseId,file);
        //根据主键id把状态设为1
        mqMessageService.completedStageOne(taskId);
    }

    private void saveCourseIndex(MqMessage mqMessage, Long courseId){
        Long taskId = mqMessage.getId();
        MqMessageService mqMessageService = this.getMqMessageService();

        int stageTwo = mqMessageService.getStageTwo(taskId);
        if (stageTwo>0){
            log.debug("添加索引完成，无需处理.....");
            return;
        }

        //从发布表中查询需要建立索引的信息
        CoursePublish coursePublish = coursePublishMapper.selectById(courseId);

        CourseIndex courseIndex = new CourseIndex();
        BeanUtils.copyProperties(coursePublish,courseIndex);
        //调用client
        Boolean add = searchServiceClient.add(courseIndex);
        if (!add){
            xuechengplusException.cast("添加索引失败,课程id："+courseId);
        }

        mqMessageService.completedStageTwo(taskId);
    }
}
